<template>
  <div class="customer" style="padding-top:0">
    <el-row class="samples-info-box">
      <el-row :gutter="10">
        <el-col :span="18">
          <el-col
            ref="moreSearch"
            :lg="18"
            class="samples-searchBar-wrapper"
            :class="{'samples-show-more':ismore}"
          >
            <el-col :lg="8" :xl="6">
              <el-input
                v-model="listQuery.code"
                clearable
                class="samples-search-input"
                placeholder="合同编号"
                size="small"
              />
            </el-col>
            <el-col :lg="8" :xl="6">
              <el-input
                v-model="listQuery.name"
                clearable
                class="samples-search-input"
                placeholder="合同名称"
                size="small"
              />
            </el-col>
            <el-col :lg="8" :xl="6">
              <el-autocomplete
                v-model="listQuery.unitName"
                size="small"
                clearable
                :fetch-suggestions="querySearch"
                value-key="companyName"
                style="width:100%"
                placeholder="单位名称"
                class="samples-search-input"
                :trigger-on-focus="false"
                @select="handleSelect"
              />

            </el-col>
            <el-col :lg="8" :xl="6">
              <el-select
                v-model="listQuery.classifyId"
                clearable
                placeholder="合同分类"
                style="width:100%"
                class="samples-search-input"
                size="small"
                @change="selectClassifyName"
                @clear="clearClassifyName"
              >
                <el-option
                  v-for="item in classifyNameList"
                  :key="item.code"
                  :label="item.name"
                  :value="item.code"
                />
              </el-select>
            </el-col>
            <el-col :lg="8" :xl="6">
              <el-select
                v-model="listQuery.typeId"
                clearable
                style="width:100%"
                placeholder="合同类型"
                class="samples-search-input"
                size="small"
              >
                <el-option
                  v-for="item in typeNameList"
                  :key="item.code"
                  :label="item.name"
                  :value="item.code"
                />
              </el-select>
            </el-col>
            <el-col :lg="8" :xl="6">
              <el-select
                v-model="listQuery.status"
                clearable
                style="width:100%"
                placeholder="状态"
                class="samples-search-input"
                size="small"
              >
                <el-option
                  v-for="item in statusNameList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-col>
            <el-col :lg="16" :xl="12">
              <el-date-picker
                v-model="searchTime"
                style="width:100%"
                size="small"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                value-format="yyyy-MM-dd"
              />
            </el-col>
          </el-col>
          <el-col :lg="6">
            <el-button size="small" type="primary" plain class="samples-search-btn" @click="searchList()">
              <i class="el-icon-search" />
            </el-button>
            <el-button
              size="small"
              type="text"
              class="samples-search-btn samples-ismore-button"
              @click="moreClick"
            >
              MORE
              <i
                class="samples-search-icon"
                :class="[ismore?'el-icon-arrow-up':'el-icon-arrow-down']"
              />
            </el-button>
          </el-col>
        </el-col>
        <!-- 右半边按钮区域 -->
        <el-col :span="6" class="samples-text-right">
          <el-button size="small" type="success" @click="handleAdd">新 增</el-button>
          <el-button size="small" type="success" :loading="loading" @click="exportExcel">导 出</el-button>

        </el-col>
      </el-row>
    </el-row>

    <el-row class="samples-info-box">
      <el-col :span="24" class="samples-text-left samples-mb-10">
        <s-table
          :column="tableData.column"
          :data="tableDatas"
          :header-cell-class-name="headerCellClass"
          pagination
          background
          layout="total, sizes, prev, pager, next, jumper"
          :page-sizes="[10,20,30,50]"
          :current-page.sync="listQuery.page"
          :total="total"
          :page-size="listQuery.pageSize"
          @size-change="handleSizeChange"
          @p-current-change="handleCurrentChange"
        />
      </el-col>
    </el-row>

    <el-dialog
      title="合同作废"
      :visible.sync="invalidVisible"
      width="960px"
      top="50vh"
      :close-on-press-escape="false"
      :close-on-click-modal="false"
      custom-class="samples-dialog"
      :append-to-body="true"
      :before-close="handleClose"
    >
      <!-- esc按钮和点击遮罩不会关闭弹窗，需要设置配置项 -->
      <el-row class="samples-dialog-box contract-invalid">
        <el-form ref="ruleForm" :model="ruleForm" class="samples-form" :rules="rules" label-width="84px">
          <el-row>
            <el-col :lg="24" :xl="{span: 22, offset: 1,pull:1}">
              <el-form-item label="作废理由：" prop="voidReason">
                <el-input v-model="ruleForm.voidReason" clearable type="textarea" maxlength="500" resize="none" size="small" :autosize="{ minRows: 4, maxRows: 10}" placeholder="请输入作废理由" />
                <template slot="error" slot-scope="scope">
                  <div class="sample-error-message">{{ scope.error }}</div>
                </template>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </el-row>

      <div class="samples-info-box  samples-pageForm" style="margin-bottom: 10px;">
        <div class="tab-upload-box">
          <el-tabs class="samples-tabs">
            <el-tab-pane v-for="(item , index) in Lists" :key="index">
              <div slot="label" class="tabs-lable">
                <span>{{ item.name }}</span>
                <span>({{ fileList[index]?fileList[index].length:0 }})</span>
              </div>
              <upload
                :multiple="false"
                :action="action"
                :file-list="fileList[index]"
                @removeList="(i)=>{return spliceList(i,index)}"
                @changeFile="files=>{return changeFileHandler(files,index)}"
              />
            </el-tab-pane>
          </el-tabs>
        </div>
      </div>
      <el-row class="samples-dialog-footer samples-mt-20">
        <el-row class="samples-float-right">
          <el-button size="small" type="primary" plain @click="handleClose">取 消</el-button>
          <el-button size="small" type="primary" @click="premitChooseContract">作 废</el-button>
        </el-row>
      </el-row>
    </el-dialog>

  </div>
</template>
<script>
import {
  insertApi,
  queryUnit,
  selectContractApi,
  deleteApi,
  detailApi,
  editApi,
  materialApi,
  getListApi,
  searchJiaYiApi,
  getContractStatusApi,
  operateApi,
  contractMagDictApi,
  getFileTagsApi,
  exportApi,
  searchJiaYiNextApi
} from '@/api/contractManage/contractMag'
import { setStore, removeStore } from '@/utils/store'
import upload from '@/components/Supload/upload'
import sTable from '@/components/STable/s-table'
import { cacheMixin } from '@/utils/mixins/clearCache'
import { request } from 'http'
export default {
  components: {
    sTable,
    upload
  },
  mixins: [cacheMixin],
  data() {
    return {
      tableDatas: [],
      unitNameList: [],
      fileList: [],
      Lists: [{ id: 99, name: '作废附件' }],
      rules: {
        voidReason: [
          { required: true, message: '请输入作废理由', trigger: 'blur' },
          {
            min: 0,
            max: 500,
            message: '不能超过500字符',
            trigger: 'blur'
          }
        ]
      },
      ruleForm: {
        voidReason: '',
        typeFlag: 30,
        attachmentList: []
      },
      loading: false,
      listQuerIed: {},
      searchTime: '',
      classifyNameList: [],
      typeNameList: [],
      statusNameList: [
        { id: 0, name: '全部' },
        { id: 1, name: '草稿' },
        { id: 10, name: '执行中' },
        { id: 20, name: '已归档' },
        { id: 30, name: '已作废' }
      ],
      deptArr: [],
      importForm: {
        type: '私池',
        deptName: '',
        deptId: ''
      },
      formRules: {},
      // 导入模块
      importDialog: false,
      uploadUrl: 'crm/customer/import',
      // upLoadData: {
      //   type: '公池'
      // },
      importHeaders: {
        TENANT_ID: '',
        Authorization: ''
      },
      establishTime: {
        // 日期不能超过将来
        disabledDate(time) {
          return time.getTime() > Date.now()
        }
      },
      ismore: false,
      dropShow: false,

      status: [], // 企业经营状态
      dialogVisible: false, // 弹出框状态
      total: 0, // 分页
      listQuery: {
        page: 1,
        pageSize: 10,
        code: '',
        name: '',
        unitName: '',
        beginTime: '',
        endTime: '',
        classifyId: '',
        typeId: '',
        status: ''
      },
      tableData: {
        column: [
          {
            prop: 'code',
            label: '合同编号',
            width: '200',
            showOverflowTooltip: true,
            fixed: true,
            className: 'samples-color-link',
            render: (h, scope) => {
              return (
                <div>
                  <a
                    style='display: block; color: #ceab70;text-decoration-line: underline;'
                    class='samples-table-overflow'
                    onClick={() => {
                      this.$router.push({
                        name: '/contractManage/contractMag/detail',
                        params: {
                          id: scope.row.id,
                          tagsName: scope.row.name
                        }
                      })
                    }}
                  >
                    {scope.row.code}
                  </a>
                </div>
              )
            }
          },
          {
            prop: 'name',
            label: '合同名称',
            width: '140'
          },
          {
            prop: 'partyAName',
            label: '甲方单位',
            width: '140',
            render: (h, scope) => {
              return (
                <span> {scope.row.partyAName} </span>
              )
            }
          },
          {
            prop: 'partyBName',
            label: '乙方单位',
            width: '140',
            render: (h, scope) => {
              return (
                <span> {scope.row.partyBName} </span>
              )
            }
          },
          {
            prop: 'amount',
            label: '合同金额',
            width: '120',
            render: (h, scope) => {
              const num = (Number(scope.row.amount).toFixed(2) + '').replace(
                /\d{1,3}(?=(\d{3})+(\.\d*)?$)/g,
                '$&,'
              )
              return <span>{num}</span>
            }
          },
          {
            prop: 'currency',
            label: '币种',
            width: '90',
            render: (h, scope) => {
              return (
                <span>人民币</span>

              )
            }
          },
          {
            prop: 'classifyName',
            label: '合同分类',
            width: '140',
            render: (h, scope) => {
              return (
                <span>{scope.row.classifyName ? scope.row.classifyName : ''}</span>

              )
            }
          },
          {
            prop: 'typeName',
            label: '合同类型',
            width: '90',
            render: (h, scope) => {
              return (
                <span>{scope.row.typeName ? scope.row.typeName : ''}</span>

              )
            }
          },
          {
            prop: 'signedTime',
            label: '签订日期',
            width: '150',
            render: (h, scope) => {
              return (
                <span>{scope.row.signedTime ? scope.row.signedTime : ''}</span>

              )
            }
          },
          {
            prop: 'statusName',
            label: '状态',
            render: (h, scope) => {
              return (
                <span>{scope.row.statusName ? scope.row.statusName : ''}</span>
              )
            }
          },
          {
            prop: 'createUserName',
            label: '创建人',
            render: (h, scope) => {
              return (
                <span>{scope.row.createUserName ? scope.row.createUserName : ''}</span>
              )
            }
          },
          {

            label: '操作',
            width: '180',
            render: (h, scope) => {
              return (
                <div>
                  <el-button
                    type='text'
                    size='small'
                    v-show={scope.row.statusName != '已作废'}
                    slot='reference'
                    style='border-width: 0px;margin-right: 15px;'
                    onClick={() => {
                      this.$router.push({
                        path: '/contractManage/contractMag/edit',
                        query: {
                          id: scope.row.id,
                          status: encodeURIComponent(scope.row.statusName)
                        }

                      })
                    }}
                  >
                      编 辑
                  </el-button>
                  <el-popover
                    placement='left'
                    trigger='click'
                    v-show={scope.row.statusName == '草稿'}
                    popper-class='s-popover'
                    width='234'
                  >
                    <div style='display:flex;align-items:center;justify-content:center;padding:20px 0;'>
                      <i
                        class='el-icon-question'
                        style='font-size:26px;margin-right:10px;color:#e05e5e'
                      />
                      确定删除这条数据吗？
                    </div>
                    <div style='text-align: center; margin: 0'>
                      <el-button
                        size='small'
                        type='primary'
                        plain
                        onClick={() => {
                          this.handleClosePopover()
                        }}
                      >
                        取 消
                      </el-button>
                      <el-button
                        type='primary'
                        size='small'
                        onClick={() => {
                          this.deletas(scope.row)
                        }}
                      >
                        确 认
                      </el-button>
                    </div>
                    <el-button
                      type='text'
                      size='small'
                      slot='reference'
                      style='border-width: 0px;'
                      class='samples-text-button-disabled'
                    >
                      删 除
                    </el-button>
                  </el-popover>
                  <el-popover
                    placement='left'
                    trigger='click'
                    v-show={scope.row.statusName == '执行中'}
                    popper-class='s-popover'
                    width='234'
                  >
                    <div style='display:flex;align-items:center;justify-content:center;padding:20px 0;'>
                      <i
                        class='el-icon-warning'
                        style='font-size:26px;margin-right:10px;color:#4f9bdb'
                      />
                      确定完成数据吗？
                    </div>
                    <div style='text-align: center; margin: 0'>
                      <el-button
                        size='small'
                        type='primary'
                        plain
                        onClick={() => {
                          this.handleClosePopover()
                        }}
                      >
                        取 消
                      </el-button>
                      <el-button
                        type='primary'
                        size='small'
                        onClick={() => {
                          this.complete(scope.row)
                        }}
                      >
                        确 认
                      </el-button>
                    </div>
                    <el-button
                      type='text'
                      size='small'
                      slot='reference'
                      class='samples-text-button-primary'
                      style='margin-right:15px;'
                    >
                      完 成
                    </el-button>
                  </el-popover>
                  <el-button
                    type='text'
                    size='small'
                    v-show={scope.row.statusName == '执行中'}
                    slot='reference'
                    class='samples-text-button-disabled'
                    onClick={() => {
                      this.invalid(scope.row)
                    }}
                  >
                      作 废
                  </el-button>

                </div>
              )
            }
          }
        ]

      },
      invalidVisible: false,
      action: '1'
    }
  },
  beforeRouteLeave(to, from, next) {
    if (to.name == '/contractManage/contractMag/detail') {
      to.meta.title = to.params.tagsName
    }
    next()
  },
  created() {
    contractMagDictApi('contract_classify').then(res => {
      this.classifyNameList = res.data
    })
    this.getList()
  },
  activated() {
    if (this.$route.query.isTag != true) {
      this.getList()
    }
  },
  methods: {
    clearClassifyName() {
      this.typeNameList = []
      this.listQuery.typeId = ''
    },
    selectClassifyName() {
      if (this.listQuery.classifyId == '001201') {
        contractMagDictApi('single_contract_type').then(res => {
          this.typeNameList = res.data
        })
      } else if (this.listQuery.classifyId == '001202') {
        contractMagDictApi('project_contract_type').then(res => {
          this.typeNameList = res.data
        })
      }
      this.listQuery.typeId = ''
    },
    premitChooseContract() {
      this.$refs['ruleForm'].validate(valid => {
        if (valid) {
          this.ruleForm.attachmentList = []

          if (this.fileList.length > 0) {
            this.fileList.forEach((item, index) => {
              item.forEach((item3, index3) => {
                item3.typeItemId = '001501'
                item3.typeItemName = '作废附件'
                item3.fileId = item3.fileUrl
                item3.fileName = item3.name
                this.ruleForm.attachmentList.push(item3)
              })
            })
          }
          this.ruleForm.id = this.contractId
          operateApi(this.ruleForm).then(res => {
            if (res.code == 1) {
              this.getList()
              this.$notify({
                title: '提示',
                message: '作废成功',
                type: 'success',
                duration: 2000
              })
              this.handleClose()
            } else {
              this.$notify({
                title: '警告',
                type: 'warning',
                message: res.msg,
                duration: '3000'
              })
            }
          })
        }
      })
    },
    deletas(row) {
      deleteApi({ id: row.id }).then(res => {
        this.handleClosePopover()
        if (res.code == 1) {
          this.getList()
          this.$notify({
            title: '提示',
            message: '删除成功',
            type: 'success',
            duration: 2000
          })
        } else {
          this.$notify({
            title: '警告',
            type: 'warning',
            message: res.msg,
            duration: '3000'
          })
        }
      })
    },
    complete(row) {
      const request = { typeFlag: 20, id: row.id, attachmentList: [] }
      operateApi(request).then(res => {
        this.handleClosePopover()
        if (res.code == 1) {
          this.getList()
          this.$notify({
            title: '提示',
            message: '完成成功',
            type: 'success',
            duration: 2000
          })
        } else {
          this.$notify({
            title: '警告',
            type: 'warning',
            message: res.msg,
            duration: '3000'
          })
        }
      })
    },

    invalid(row) {
      this.contractId = row.id
      this.invalidVisible = true
    },

    changeFileHandler(files, index) {
      this.$set(this.fileList, index, files)
    },
    spliceList(i, index) {
      const filelist = JSON.parse(JSON.stringify(this.fileList[index]))

      filelist.splice(i, 1)

      this.$set(this.fileList, index, filelist)

      const files = []
      for (let i = 0; i < this.fileList.length; i++) {
        if (this.fileList[i] !== undefined) {
          for (let j = 0; j < this.fileList[i].length; j++) {
            const obj = {}
            this.fileList[i][j]
            obj.fileId = this.fileList[i][j].fileUrl
            obj.name = this.fileList[i][j].name
            obj.size = this.fileList[i][j].size
            // obj.type = this.Lists[i].nodeName
            // obj.companyId = this.editForm.id
            files.push(obj)
          }
        }
      }
      updateFile(files).then(res => {
        if (res.code == '0') {

          // this.getCustomerinfo(this.editForm.id);
        } else {
          this.$notify({
            title: '错误',
            type: 'error',
            message: res.msg
          })
        }
      })
    },
    // 获取列表
    exportExcel() {
      this.loading = true
      const request = Object.assign({}, request, this.listQuerIed)
      request.page = ''
      request.pageSize = ''
      exportApi(request).then(res => {
        if (res.code == 1) {
          if (res.data.length == 0) {
            this.loading = false
            this.$notify({
              title: '提示',
              type: 'warning',
              message: '无列表数据',
              duration: '3000'
            })
            return
          }
          const resImport = res
          import('@/vendor/Export2Excel').then(excel => {
            const tHeader = ['合同编号', '合同名称', '甲方单位', '乙方单位', '业务单元', '所属项目', '合同分类', '合同类型', '合同金额', '签订日期', '合同内容', '状态', '创建人']
            // const data = [['sssss撒士大夫胜多负少', 2]]
            const data = []

            resImport.data.forEach(item => {
              item.amount = (Number(item.amount).toFixed(2) + '').replace(
                /\d{1,3}(?=(\d{3})+(\.\d*)?$)/g,
                '$&,'
              )
              data.push([item.code, item.name, item.partyAName, item.partyBName, item.businessUnitName,
                item.projectName, item.classifyName, item.typeName, item.amount, item.signedTime, item.content, item.statusName, item.createUserName])
            })

            excel.export_json_to_excel({
              header: tHeader, // 表头 必填
              data, // 具体数据 必填
              filename: '合同信息明细', // 非必填
              autoWidth: true, // 非必填
              bookType: 'xlsx', // 非必填
              sheetJsName: '合同信息明细',
              title: '合同信息明细'
            })
            this.loading = false
          })
        } else {
          this.loading = false
          this.$notify({
            title: '警告',
            type: 'warning',
            message: res.msg,
            duration: '3000'
          })
        }
      })
    },
    // 获取列表
    getList() {
      const request = Object.assign({}, request, this.listQuery)
      if (this.searchTime) {
        request.beginTime = this.searchTime[0]
        request.endTime = this.searchTime[1]
      } else {
        request.beginTime = ''
        request.endTime = ''
      }
      request.status ? true : request.status = ''
      getListApi(request).then(res => {
        // console.log(res.data);
        if (res.code == 1) {
          this.tableDatas = res.data.records
          this.total = res.data.total
          this.listQuerIed = request
        } else {
          this.$notify({
            title: '警告',
            type: 'warning',
            message: res.msg,
            duration: '3000'
          })
        }
      })
    },
    // 查询单位名称
    querySearch(queryString, cb) {
      var query = {
        companyName: queryString
      }
      this.unitNameList = []
      Promise.all([searchJiaYiApi(query), searchJiaYiNextApi(query)]).then(res => {
        if (res[1].code == 1 && res[1].data.data) {
          this.unitNameList = this.unitNameList.concat(res[0].data.data).concat(res[1].data.data)
          cb(this.unitNameList)
        } else {
          this.$notify({
            title: '警告',
            type: 'warning',
            message: '查询失败',
            duration: '3000'
          })
          return
        }
      })
    },
    handleSelect(item) {
      console.log(item)
    },
    headerCellClass({
      row,
      column,
      rowIndex,
      columnIndex
    }) {
      if (column.type === 'index') {
        return 'indexTableHeaderStyle'
      } else if (column.type === 'selection') {
        return ''
      } else {
        return 'samples-header-cell'
      }
    },

    handleClosePopover() {
      document.querySelector('#app').click()
    },
    moreClick() {
      this.ismore = !this.ismore
      const ref = this.$refs.moreSearch.$el
      if (this.ismore) {
        ref.style.height = ref.scrollHeight + 'px'
      } else {
        ref.style.height = '32px'
      }
    },
    //   分页
    handleSizeChange(val) {
      this.listQuery.pageSize = val
      this.listQuery.page = 1
      this.getList()
    },
    handleCurrentChange(val) {
      this.listQuery.page = val
      this.getList()
    },
    handleClose(e) {
      this.fileList = []
      this.invalidVisible = false
      this.$refs['ruleForm'].resetFields()
    },
    // 打开表单的操作
    handleAdd() {
      this.clearCache('contractMag/index')
      // this.$router.push({ path: '/contractManage/contractMag/insert', query: { }})
      this.$router.push('/contractManage/contractMag/insert')
    },

    // 按顺序获取用户列表
    searchList() {
      this.listQuery.page = 1
      this.getList()
    }

  }
}
</script>

<style lang="scss">
.contract-invalid {
  .el-form-item__content{
        margin-left: 84px;
  }
}

</style>

